'''
合并两个有序链表
'''
from com.siyuan.ListNode import ListNode


class Solution:

    '''归并'''
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        if not l1 and not l2:
            return []
        if not l1:
            return l2
        if not l2:
            return l1

        res: ListNode = ListNode(0)
        tmp: ListNode = res
        while l1 or l2:
            if not l1:
                tmp.next = l2
                break
            elif not l2:
                tmp.next = l1
                break
            else:
                val = 0
                if l1.val < l2.val:
                    val = l1.val
                    l1 = l1.next
                else:
                    val = l2.val
                    l2 = l2.next
                tmp.next = ListNode(val)
                tmp = tmp.next
        return res.next


if __name__ == '__main__':
    l1 = ListNode(1)
    l1.next = ListNode(2)
    l1.next.next = ListNode(4)

    l2 = ListNode(1)
    l2.next = ListNode(3)
    l2.next.next = ListNode(4)

    sl = Solution()
    res = sl.mergeTwoLists(l1, l2)
    while res:
        print(res.val)
        res = res.next
